let current = 1;
let pageSize = 3;

// 动态生成表格
function renderTable(data) {
  $('#student-table tbody').text('');
  for (var i = 0; i < data.length; i++) {
    var tr = `
      <tr>
          <td><input type="checkbox" class="book-state"></td>
          <td>${data[i].studentName}</td>
          <td>${data[i].className}</td>
          <td>
            <button type="button" class="layui-btn view" data-studentid="${data[i].studentId}">查看</button>
            <button class="layui-btn layui-btn-normal edit" data-studentid="${data[i].studentId}">编辑</button>
            <button type="button" class="layui-btn layui-btn-danger del" data-studentid="${data[i].studentId}">删除</button>
          </td>
        </tr>
    `;
    $('#student-table tbody').append($(tr));
  }
}

function initStudent() {
  $.ajax({
    url: '/students/get',
    method: 'GET',
    data: {
      current,
      pageSize
    }
  })
    .done(function (res) {
      console.log('请求成功：', res);

      renderTable(res.data);
    })
    .fail(function (err) {
      console.log('请求失败：', err);
    });
}

// 事件委托-删除
$('#student-table').on('click', '.del', function () {
  // console.log($(this).attr('data-studentid'));
  const studentId = $(this).attr('data-studentid');

  $.ajax({
    url: '/students/del',
    method: 'POST',
    data: {
      studentId: studentId
    }
  })
    .done(function (data) {
      layer.msg(data.msg);
      initStudent();
    })
    .fail(function (err) {
      console.log(err);
      layer.msg(err.msg);
    })
});

// 事件委托-查看
$('#student-table').on('click', '.view', function () {
  const studentId = $(this).attr('data-studentid');

  parent.editIframe('student_edit.html?studentid=' + studentId + '&view=1');
});

// 事件委托-编辑
$('#student-table').on('click', '.edit', function () {
  const studentId = $(this).attr('data-studentid');

  parent.editIframe('student_edit.html?studentid=' + studentId);
});

// 新增学生
$('#add-student').on('click', function () {
  parent.editIframe('student_edit.html');
});

// 分页
layui.use('laypage', function () {
  var laypage = layui.laypage;

  $.ajax({
    url: '/students/total',
    method: 'GET'
  })
    .done(function (res) {
      console.log(res);

      laypage.render({
        elem: 'pagination', //注意，这里的 test1 是 ID，不用加 # 号
        limit: pageSize,
        count: res.data.total,
        jump: function (obj, first) {
          current = obj.curr;

          initStudent();
          //首次不执行
          if (!first) {
            //do something
          }
        }
      });
    })
    .fail(function (err) {
      console.log(err);
    })
});